import { defineStore } from 'pinia';
// 引入api
import { loginRequest, getUserInfo, logOut } from '@/api/user/user';
// 引入数据类型
import { loginForm, loginResponseData, userInfoReponseData } from '@/api/user/type';
import { userStateType } from './types';
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
// 引入路由(常量路由)
import { constantRoute, asnycRoute, anyRoute } from '@/route/routes';
import router from '@/route';
import cloneDeep from 'lodash/cloneDeep';
//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    // debugger;
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}

// 创建小仓库
let useUserStore = defineStore('user', {
  // 存储数据
  state: (): userStateType => ({
    token: GET_TOKEN(),
    menuRoutes: constantRoute, // 左侧路由菜单数组
    username: '',
    avatar: '',
    //存储当前用户是否包含某一个按钮
    buttons: [],
  }),
  actions: {
    // 用户登录
    async userLoginAction(data: loginForm) {
      const result: loginResponseData = await loginRequest(data);
      console.log('result', result);
      if (result.code == 200) {
        this.token = result.data as string;
        SET_TOKEN(result.data as string);
        return 'ok';
      } else {
        console.log('result.data', result.data);
        return Promise.reject(new Error(result.data as string));
      }
    },
    // 获取用户信息
    async userInfo() {
      const result: userInfoReponseData = await getUserInfo();
      console.log('用户信息', result);

      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.buttons = result.data.buttons;
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), result.data.routes);
        console.log('过滤后的路由', userAsyncRoute);
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
        // 追加任意路由以及异步路由
        [...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route);
        });
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message as string));
      }
    },
    // 退出登录
    async getlogout() {
      const result: any = await logOut();
      console.log('退出登录', result);
      if (result.code === 200) {
        this.token = '';
        this.username = '';
        this.avatar = '';
        REMOVE_TOKEN();
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
  },
  // 计算属性
  getters: {},
});

export default useUserStore;
